package pl.enigmatic.math;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class LatticeMap<K, V> {

	private final Map<K, Map<K, V>> map = new HashMap<K, Map<K, V>>();

	public void clear() {
		map.clear();
	}

	public boolean containsKey(final K key1, final K key2) {
		return map.containsKey(key1) && map.get(key1).containsKey(key2);
	}

	public V get(final K key1, final K key2) {
		return map.containsKey(key1) ? map.get(key1).get(key2) : null;
	}

	public V put(final K key1, final K key2, final V value) {
		if (!map.containsKey(key1)) {
			map.put(key1, new HashMap<K, V>());
		}
		return map.get(key1).put(key2, value);
	}

	public boolean isEmpty() {
		if (!map.isEmpty()) {
			final Iterator<Map<K, V>> i = map.values().iterator();
			Map<K, V> last = null;
			while (i.hasNext() && (last = i.next()).isEmpty()) {
				;
			}
			return last == null || last.isEmpty();
		}
		return false;
	}

	public Collection<V> values() {
		final Set<V> set = new HashSet<V>();
		for (final Map<K, V> val : map.values()) {
			set.addAll(val.values());
		}
		return set;
	}

	public Set<Entry<K, Map<K, V>>> entrySet() {
		return map.entrySet();
	}
}
